<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use FormBuilder\Factory\Elm;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\admin\validate\MassageCoupon as ValidateMassageCoupon;
use plugin\ycMassage\app\model\MassageCoupon;
use plugin\ycMassage\utils\enum\CouponReceiveType;
use plugin\ycMassage\utils\enum\CouponUseType;
use plugin\ycMassage\utils\enum\CouponValidType;
use plugin\ycMassage\utils\enum\State;
use think\Request;

class CouponController extends BaseController
{
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addTopButton('add', '创建优惠券', [
            'api'       => $this->pluginPrefix . '/admin/Coupon/create',
            'path' => '/Coupon/create',
            'type'      => 'modal',
            'queryParams' => [
                'position' => 'banner'
            ]
        ], [
            'title' => '创建优惠券',
        ], [
            'type' => 'success'
        ]);
        $builder->addRightButton('edit', '修改', [
            'api'    => $this->pluginPrefix . '/admin/Coupon/update',
            'path' => '/Coupon/update',
            'type'      => 'modal'
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('issue', '发行优惠券码', [
            'api'    => $this->pluginPrefix . '/admin/CouponCode/issue',
            'path' => '/CouponCode/issue',
            'type'      => 'modal'
        ], [
            'title' => '发行优惠券码',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90
        ])
            ->addColumn('title', '优惠券')
            ->addColumn('passowrd', '领取口令')
            ->addColumnEle('money', '面值', [
                'width' => 100,
                'params' => [
                    'type' => 'money',
                ],
            ])
            ->addColumnEle('use_type', '使用方式', [
                'width'  => 120,
                'params' => [
                    'type'    => 'tags',
                    'options' => CouponUseType::dictOptions(),
                ],
            ])
            ->addColumnEle('full_money', '满减金额', [
                'width' => 100,
                'params' => [
                    'type' => 'money',
                ],
            ])

            ->addColumnEle('valid_type', '有效时间方式', [
                'width'  => 120,
                'params' => [
                    'type'    => 'tags',
                    'options' => CouponValidType::dictOptions(),
                ],
            ])
            ->addColumn('valid_time', '有效期', [
                'width' => 100,
            ])
            ->addColumn('valid_day', '领取后(天)', [
                'width' => 100,
            ])
            ->addColumnEle('receive_type', '领取方式', [
                'width'  => 120,
                'params' => [
                    'type'    => 'tags',
                    'options' => CouponReceiveType::dictOptions(),
                    'style' => [
                        'BIND' => [
                            'type' => 'danger'
                        ]
                    ]
                ],
            ])
            ->addColumn('sum', '总发行')
            ->addColumn('num', '剩余')
            ->addColumn('receive_num', '已领取')
            ->addColumn('use_num', '已使用')
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type' => 'switch',
                    'api' => $this->pluginPrefix . '/admin/Coupon/updateState',
                    'checked' => [
                        'text' => '可用',
                        'value' => 1
                    ],
                    'unchecked' => [
                        'text' => '不可用',
                        'value' => 0
                    ]
                ],
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['saas_appid', '=', $request->saas_appid]
        ];
        $title = $request->get('title');
        if ($title) {
            $where[] = ['title', 'like', "%{$title}%"];
        }
        $data = MassageCoupon::where($where)
            ->order('id desc')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
            });
        return $this->successRes($data);
    }
    public function create(Request $request)
    {
        if ($request->method() === 'POST') {
            $D = $request->post();
            hpValidate(ValidateMassageCoupon::class, $D);
            $MassageCoupon = new MassageCoupon();
            $D['saas_appid'] = $request->saas_appid;
            if (empty($D['receive_day'])) {
                unset($D['receive_day']);
            }
            if ($MassageCoupon->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($builder);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function update(Request $request)
    {
        $id = $request->get('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageCoupon = MassageCoupon::where($where)->find();
        if (!$MassageCoupon) {
            return $this->fail('该优惠券不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            hpValidate(ValidateMassageCoupon::class, $D);
            $D['saas_appid'] = $request->saas_appid;
            if (empty($D['receive_day'])) {
                $MassageCoupon->receive_day = null;
                unset($D['receive_day']);
            }
            if ($MassageCoupon->save($D)) {
                return $this->success('添加成功');
            }
            return $this->fail('添加失败');
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $this->getFormBuilder($builder);
        $data = $builder->setData($MassageCoupon)->create();
        return $this->successRes($data);
    }
    public function getFormBuilder($builder)
    {
        $builder->addRow('title', 'input', '名称', '', [
            'col' => 12,
        ]);
        $builder->addRow('password', 'input', '领取口令', '', [
            'col' => 12,
        ]);
        $builder->addRow('state', 'radio', '状态', 1, [
            'col' => 12,
            'options' => State::getOptions()
        ]);
        $builder->addComponent('money', 'input-number', '面值', 0, [
            'col' => 12,
            'props' => [
                'controls' => false,
                'min' => 0,
                'precision' => 2
            ],
        ]);
        $control = [
            [
                'value' => CouponValidType::TIME['value'],
                'where' => '==',
                'rule' => [
                    Elm::dateRange('valid_time', '有效时间', null, null)
                        ->col([
                            'span' => 12
                        ])
                        ->props([
                            'type' => 'datetimerange',
                            'format' => 'YYYY-MM-DD HH:mm:ss',
                            'value-format' => 'YYYY-MM-DD HH:mm:ss',
                            'start-placeholder' => '开始时间',
                            'end-placeholder' => '结束时间',
                        ])
                ],
            ],
            [
                'value' => CouponValidType::DAY['value'],
                'where' => '==',
                'rule' => [
                    Elm::number('valid_day', '有效天数')
                        ->col([
                            'span' => 12
                        ])
                        ->props([
                            'controls' => false,
                            'min' => 0,
                            'precision' => 0
                        ])
                ],
            ]
        ];
        $builder->addRow('valid_type', 'radio', '有效时间方式', CouponValidType::TIME['value'], [
            'col' => 12,
            'options' => CouponValidType::getOptions(),
            'control' => $control
        ]);
        $control = [
            [
                'value' => CouponUseType::FULL_DEC['value'],
                'where' => '==',
                'rule' => [
                    Elm::number('full_money', '满减金额')
                        ->col([
                            'span' => 12
                        ])
                        ->props([
                            'controls' => false,
                            'min' => 0,
                            'precision' => 2
                        ])
                ],
            ],
        ];
        $builder->addRow('use_type', 'radio', '使用方式', CouponUseType::DEC['value'], [
            'col' => 12,
            'options' => CouponUseType::getOptions(),
            'control' => $control
        ]);
        $week = [
            [
                'label' => '周一',
                'value' => 1
            ],
            [
                'label' => '周二',
                'value' => 2
            ],
            [
                'label' => '周三',
                'value' => 3
            ],
            [
                'label' => '周四',
                'value' => 4
            ],
            [
                'label' => '周五',
                'value' => 5
            ],
            [
                'label' => '周六',
                'value' => 6
            ],
            [
                'label' => '周日',
                'value' => 0
            ]
        ];
        $month = [];
        for ($i = 1; $i <= 28; $i++) {
            $month[] = [
                'label' => $i . '日',
                'value' => $i
            ];
        }
        $month[] = [
            'label' => '月末',
            'value' => 99
        ];
        $control = [
            [
                'value' => CouponReceiveType::WEEK['value'],
                'where' => '==',
                'rule' => [
                    Elm::radio('receive_day', '周几可领')
                        ->col([
                            'span' => 24
                        ])
                        ->options($week)
                        ->props([
                            'border' => true
                        ])
                ],
            ],
            [
                'value' => CouponReceiveType::MONTH['value'],
                'where' => '==',
                'rule' => [
                    Elm::select('receive_day', '每月几号可领')
                        ->col([
                            'span' => 12
                        ])
                        ->options($month)
                        ->props([
                            'clearable' => true
                        ])
                ],
            ],
        ];
        $builder->addRow('receive_type', 'radio', '领取方式', CouponReceiveType::BIND['value'], [
            'col' => 12,
            'options' => CouponReceiveType::getOptions(),
            'control' => $control
        ]);
    }
    public function updateState(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageCoupon = MassageCoupon::where($where)->find();
        if (!$MassageCoupon) {
            return $this->fail('该优惠券不存在');
        }
        $MassageCoupon->state = $request->post('value');
        if ($MassageCoupon->save()) {
            return $this->success('修改成功');
        }
        return $this->fail('修改失败');
    }
}
